import { getSettingRecord, startVoiceRecord, stopVoiceRecord } from "../../utils/util"
import formatXml from '../../utils/parseXML'
import { DOMParser } from "xmldom"
import { Base64 } from "js-base64";
const APPID = '87524629'
const API_SECRET = 'ODQzZDk3NTUxMWEwZmMxYjA5ZDc1YmE4'
const API_KEY = 'b93706ebb256c68f7a0a4ac58fc87251'
const CryptoJS = require('crypto-js')
let audioData = [] //存储音频流的数组
let socketTask = null //小程序的socketTask
let handlerInterval = null // 定时器，用来定时发送数据流
// pages/demo/index.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    recordState: false, //录音状态
    renderText: "",//渲染的文字
  },
  //音频转码(步骤二)[把音频片段转换成base64]
  toBase64(buffer) {
    return wx.arrayBufferToBase64(buffer);
  },
  getWebSocketUrl() {//生成socket使用的url

    // const Base64 = require('../../utils/tools/base64js').Base64;
    var DOMParser = require('xmldom').DOMParser;
    return new Promise((resolve, reject) => {
      var url = 'wss://ise-api.xfyun.cn/v2/open-ise'
      var host = 'ise-api.xfyun.cn'
      var apiKey = API_KEY
      var apiSecret = API_SECRET
      var date = new Date().toUTCString()
      var algorithm = 'hmac-sha256'
      var headers = 'host date request-line'
      var signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v2/open-ise HTTP/1.1`
      var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret)
      var signature = CryptoJS.enc.Base64.stringify(signatureSha)

      var authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`
      let authStr = CryptoJS.enc.Base64.stringify(
        CryptoJS.enc.Utf8.parse(authorizationOrigin)
      );
      console.log(authorizationOrigin);
      // var authorization = Base64(authorizationOrigin)
      // 获取当前时间 RFC1123格式
      //科大讯飞远程连接地址
      url = `${url}?authorization=${authStr}&date=${date}&host=${host}`
      resolve(url)
    })
  },
  webSocketSend() {
    console.log('开始发送数据', audioData)
    let that = this
    let audioDataUp = audioData.splice(0, 1)
    var params = {
      common: {
        app_id: APPID,
      },
      business: {
        category: 'read_sentence', // read_syllable/单字朗读，汉语专有 read_word/词语朗读  read_sentence/句子朗读 https://www.xfyun.cn/doc/Ise/IseAPI.html#%E6%8E%A5%E5%8F%A3%E8%B0%83%E7%94%A8%E6%B5%81%E7%A8%8B
        rstcd: 'utf8',
        group: 'pupil',
        sub: 'ise',
        ent: 'cn_vip',
        tte: 'utf-8',
        cmd: 'ssb',
        auf: 'audio/L16;rate=16000',
        aus: 1,
        aue: 'raw',
        text: '\uFEFF' + '今天天气怎么样？',
        language: "zh_cn",
      },
      data: {
        status: 0,
        encoding: 'raw',
        data_type: 1,
        data: that.toBase64(audioDataUp[0]),
      },
    }
    console.log(JSON.stringify(params))
    socketTask.send({ data: JSON.stringify(params) })
    handlerInterval = setInterval(() => {
      // websocket未连接
      if (!socketTask) {
        clearInterval(handlerInterval)
        return
      }
      // 最后一帧
      if (audioData.length === 0) {
        console.log('数据发送完毕')
        socketTask.send(
          {
            data:
              JSON.stringify({
                business: {
                  cmd: 'auw',
                  aus: 4,
                  aue: 'raw'
                },
                data: {
                  status: 2,
                  encoding: 'raw',
                  data_type: 1,
                  data: '',
                },
              })
          }
        )
        audioData = []
        clearInterval(handlerInterval)

        return false
      }
      audioDataUp = audioData.splice(0, 1)
      // 中间帧
      console.log('audioDataUp:', audioDataUp[0])
      socketTask.send(
        {
          data:
            JSON.stringify({
              business: {
                cmd: 'auw',
                aus: 2,
                aue: 'raw'
              },
              data: {
                status: 1,
                encoding: 'raw',
                data_type: 1,
                data: that.toBase64(audioDataUp[0]),
              },
            })
        }
      )
    }, 40)
  },
  result(resultData) {
    console.log(resultData);
    // 识别结束
    let jsonData = JSON.parse(resultData)
    let data = Base64.decode(jsonData.data.data)
    if (jsonData.data && jsonData.data.data) {
      let data = jsonData.data.data
      var arrayBuffer = wx.base64ToArrayBuffer(data);
      // 将ArrayBuffer对象转换为Uint8Array对象
      var uint8Array = new Uint8Array(arrayBuffer);
      // 将Uint8Array对象转换为字符串
      var decodedString = String.fromCharCode.apply(null, uint8Array);
      console.log(decodedString);
      const doc = new DOMParser().parseFromString(decodedString, 'text/xml');

      let sentence = doc.getElementsByTagName('read_sentence')[1]
      let accuracy_score = sentence.getAttribute('accuracy_score')
      let emotion_score = sentence.getAttribute('emotion_score')
      let fluency_score = sentence.getAttribute('fluency_score')
      let total_score = sentence.getAttribute('total_score')
      let content = sentence.getAttribute('content')

      console.log('parseRes:',accuracy_score,emotion_score,fluency_score,total_score,content)
      //评测结果在这里，就出来了，然后就可以拿评测数据去使用了

    }
    if (jsonData.code === 0 && jsonData.data.status === 2) {
      // 在这里结束socket
      socketTask.close()
    }
    if (jsonData.code !== 0) {
      socketTask.close()
      console.log(`${jsonData.code}:${jsonData.message}`)
    }
  },

  startUpRecord() {
    let that = this
    that.getWebSocketUrl().then((url) => {
      console.log(url);
      let newURL = encodeURI(url)
      socketTask = wx.connectSocket({
        url: newURL,
      })
      socketTask.onOpen(() => {
        console.log('打开了socket')
        that.webSocketSend()
      })
      socketTask.onMessage((e) => {
        // result 在这里做信息处理
        console.log('收到了结果：', e)
        that.result(e.data)
      })
      socketTask.onError((err) => {
        //结束录音
        console.log('socket 出错：', err)
      })
      socketTask.onClose(() => {
        // 结束录音
        console.log('socket 关闭：')
      })
    })
  },

  //语音  --按住说话
  touchStart: function (e) {
    // getSettingRecord()

    // this.setData({
    //   recordState: true  //录音状态
    // })
    // startVoiceRecord()
    //开始录音
    let that = this
    let recorderManager = wx.getRecorderManager()
    that.setData({ recordState: true })
    recorderManager.onStart(() => {
      console.log('recorder start')
    })
    recorderManager.onPause(() => {
      console.log('recorder pause')
    })

    recorderManager.onFrameRecorded((res) => {
      const { frameBuffer } = res
      console.log('frameBuffer.byteLength', frameBuffer.byteLength)
      let u8Arr = new Uint8Array(frameBuffer)
      audioData.push(u8Arr) //将每一帧的数据取出，放到audioData中，准备使用
    })

    const options = {
      duration: 180000,
      sampleRate: 16000,
      numberOfChannels: 1,
      encodeBitRate: 44100,
      frameSize: 2,
      format: 'pcm',
    }
    recorderManager.start(options)
  },
  //语音  --松开结束
  touchEnd: function (e) {
    let that = this
    this.setData({
      recordState: false
    })
    let recorderManager = wx.getRecorderManager()
    recorderManager.stop()
    recorderManager.onStop((res) => {
      console.log('recorder stop', res)
      const { tempFilePath } = res
      that.startUpRecord()//录音完成，准备调用讯飞接口
    })
    // stopVoiceRecord((e) => console.log(e))
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})